package com.zjzywl.smoke.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.zjzywl.smoke.authenticate.AuthUser;
import com.zjzywl.smoke.config.BaseDataConfig;
import com.zjzywl.smoke.repository.AlarmReasonsRepository;
import com.zjzywl.smoke.repository.AlarmRepository;
import com.zjzywl.smoke.repository.SysUserRepository;
import com.zjzywl.smoke.repository.YoyRepository;
import com.zjzywl.smoke.service.AlarmReasonsService;
import com.zjzywl.smoke.service.AlarmService;
import com.zjzywl.smoke.service.SysUserService;
import com.zjzywl.smoke.service.YoyService;
import com.zjzywl.smoke.util.DataUill;
import com.zjzywl.smoke.util.MQWebSocket;
import com.zjzywl.smoke.util.WebResult;
import com.zjzywl.smoke.util.NotDispose;
import com.zjzywl.smoke.entity.Alarm;
import com.zjzywl.smoke.entity.AlarmReasons;
import com.zjzywl.smoke.entity.SysUser;
import com.zjzywl.smoke.entity.Yoy;

@RestController
@RequestMapping(value = "/alarm")
@PreAuthorize("hasAuthority('viewer')")
public class AlarmController extends BaseController {
	@Autowired
	private AlarmService alarmService;
	@Autowired
	private SysUserService userService;
	@Autowired
	private AlarmReasonsService alarmReasonsService;
	@Autowired
	private YoyService yoyService;
	@Autowired
	private AlarmRepository alarmRepository;
	
	DataUill dataUtil = new DataUill();

	@RequestMapping(value = "/data/list")

	public WebResult getAlarms() {
		List<Alarm> alarms = alarmService.findAll();
		try {
			return WebResult.OK(alarms);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 按照时间段查询
	@RequestMapping(value = "/data/list/{beginTime}/{endTime}")

	public WebResult getAlarmsByTime(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		List<Alarm> alarms = alarmService.findByBeginTimeBetweenOrderByBeginTime(bTime, eTime);
		try {
			return WebResult.OK(alarms);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 按照时间段及设备编码查询
	@RequestMapping(value = "/data/list/{beginTime}/{endTime}/{devcode}")

	public WebResult getAlarmsByTimeAndCode(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime, @PathVariable("devcode") String devcode) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		List<Alarm> alarms = alarmService.findByBeginTimeAndDevCode(bTime, eTime, devcode);
		try {
			return WebResult.OK(alarms);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 按照时间段及设备编码查询
	@RequestMapping(value = "/data/list/byaddress/{beginTime}/{endTime}/{address}")

	public WebResult getAlarmsByTimeAndAddress(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime, @PathVariable("address") String address) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		List<Alarm> alarms = alarmService.findByBeginTimeAndAddress(bTime, eTime, address);
		try {
			return WebResult.OK(alarms);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 按照时间段及设备编码、报警类型查询
	@RequestMapping(value = "/data/list/byDevcodeAndAlarmTypeCode/{beginTime}/{endTime}/{devcode}/{alarmTypeCode}")

	public WebResult getByBeginTimeAndDevCodeAndAlarmTypeCode(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime, @PathVariable("devcode") String devcode,
			@PathVariable("alarmTypeCode") String alarmTypeCode) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		List<Alarm> alarms = alarmService.findByBeginTimeAndDevCodeAndAlarmTypeCode(bTime, eTime, devcode, alarmTypeCode);
		try {
			return WebResult.OK(alarms);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 按照时间段及报警类型查询
	@RequestMapping(value = "/data/list/byAlarmTypeCode/{beginTime}/{endTime}/{alarmTypeCode}")

	public WebResult getByBeginTimeAndDevCodeAndAlarmTypeCodeAndDeviceTypeCode(
			@PathVariable("beginTime") String beginTime, @PathVariable("endTime") String endTime,
			@PathVariable("alarmTypeCode") String alarmTypeCode) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		List<Alarm> alarms = alarmService.findByBeginTimeAndAlarmTypeCode(bTime, eTime, alarmTypeCode);
		try {
			return WebResult.OK(alarms);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 报警历史记录查询 新接口
	@GetMapping(value = "/data/history/list")
	public WebResult getAlarm(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode, @PathParam("deviceTypeId") String deviceTypeId,
			@PathParam("address") String address) {
//		String userId = this.getUserId();
		System.out.println(beginTime+endTime+alarmTypeCode+
				deviceTypeId+address+1+"");
		List alarms = alarmService.getAlarmByTimeAndAlarmTypeAndAddressAndUser(beginTime, endTime, alarmTypeCode,
				deviceTypeId, address, 1+"");

		return WebResult.OK(alarms);
	}

	// 报警历史记录查询 新接口--返回数据精简
	@GetMapping(value = "/data/history/simple/list/{beginTime}/{endTime}/{alarmTypeCode}/{deviceTypeId}/{address}/{userId}")

	public WebResult getAlarmSimple(@PathVariable("beginTime") String beginTime, @PathVariable("endTime") String endTime,
			@PathVariable("alarmTypeCode") String alarmTypeCode, @PathVariable("deviceTypeId") String deviceTypeId,
			@PathVariable("address") String address,@PathVariable("userId") String userId) {
		System.out.println(beginTime+endTime+alarmTypeCode+
				deviceTypeId+address+userId);
		List alarms = alarmService.getAlarmByTimeAndAlarmTypeAndAddressAndUser(beginTime, endTime, alarmTypeCode,
				deviceTypeId, address, userId);

		return WebResult.OK(alarms);
	}

	// 按照时间段统计设备的报警数量
	@RequestMapping(value = "/data/device/count/{beginTime}/{endTime}")

	public WebResult getDeviceAlarmCount(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime, @PathVariable("alarmTypeCode") String alarmTypeCode) {
		String bTime = beginTime;
		String eTime = endTime;

		String count = appConfig.getFocusByCount();
		if (count.length() > 0) {
			List alarms = alarmService.getDeviceAlarmCountByTime(bTime, eTime, Integer.valueOf(count));
			return WebResult.OK(alarms);
		} else {
			return WebResult.FAIL("获取配置文件FocusByCount信息出错！");
		}
	}

	// 按照时间段统计设备的报警数量
	@RequestMapping(value = "/data/device/count")

	public WebResult getDeviceAlarmCountEx(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmTypeCode") String alarmTypeCode,
			@PathParam("deviceTypeId") String deviceTypeId) {
		String bTime = beginTime;
		String eTime = endTime;

		String count = appConfig.getFocusMoveByCount();
		String userId = this.getUserId();
		if (count.length() > 0) {
			List alarms = alarmService.getDeviceAlarmCountByTimeEx(bTime, eTime, Integer.valueOf(count), alarmTypeCode,
					deviceTypeId, userId);
			return WebResult.OK(alarms);
		} else {
			return WebResult.FAIL("获取配置文件FocusMoveByCount信息出错！");
		}
	}

	// 临时：按照时间段统计设备的报警数量
	@RequestMapping(value = "/data/device/countEx")

	public WebResult getDeviceAlarmCount(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode, @PathParam("deviceTypeId") String deviceTypeId) {
		String bTime = beginTime;
		String eTime = endTime;

		String count = appConfig.getFocusMoveByCount();
		String userId = this.getUserId();
		if (count.length() > 0) {
			List alarms = alarmService.getDeviceAlarmCountByTimeEx(bTime, eTime, Integer.valueOf(count), alarmTypeCode,
					deviceTypeId, userId);
			List result = new ArrayList<>();
			for (Object fixedPlace : alarms) {
				Map value = new HashMap<String, String>();
				Object[] cells = (Object[]) fixedPlace;
				value.put("value", cells[1]);
				value.put("name", cells[0]);
				result.add(value);

			}
			return WebResult.OK(result);
		} else {
			return WebResult.FAIL("获取配置文件FocusMoveByCount信息出错！");
		}
	}

	// 按照时间查询报警数量
	// aaa
	@RequestMapping(value = "/data/device/getcount")

	public WebResult getAlarmCountEx(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode) {
		String bTime = beginTime;
		String eTime = endTime;

		String userId = this.getUserId();
		List alarms = alarmService.getAlarmCountByTime(bTime, eTime, alarmTypeCode, userId);
		return WebResult.OK(alarms);

	}

	// 按照时间段、组织统计每天报警数量
	@RequestMapping(value = "/data/org/count/{beginTime}/{endTime}")

	public WebResult getOrgAlarmCount(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime) {
		String bTime = beginTime;
		String eTime = endTime;

		List alarms = alarmService.getOrgAlarmCountByTime(bTime, eTime, 0);
		return WebResult.OK(alarms);
	}

	// 按照时间段、组织统计每天报警数量
	@RequestMapping(value = "/data/org/device/count")

	public WebResult getOrgAlarmCountByTimeEx(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmTypeCode") String alarmTypeCode,
			@PathParam("deviceTypeId") String deviceTypeId) {
		String bTime = beginTime;
		String eTime = endTime;

		String userId = this.getUserId();

		List alarms = alarmService.getOrgAlarmCountByTimeEx(bTime, eTime, 0, alarmTypeCode, deviceTypeId, userId);
		return WebResult.OK(alarms);

	}

	// 查询当日火灾报警的数量
	@RequestMapping(value = "/data/device/firecount")

	public WebResult getFireByCount(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeId") int alarmTypeId) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		int count = alarmService.findByBegin(bTime, eTime, alarmTypeId);
		return WebResult.OK(count);
	}

	// 获取列入重点关注的数量条件
	@RequestMapping(value = "/data/device/focusbycount")

	public WebResult getFocusByCount() {
		return WebResult.OK(appConfig.getFocusByCount());
	}

	// 获取未处理报警
	@RequestMapping(value = "/data/notdispose")

	public WebResult getNotDispose() {
		List alarms = alarmService.findByDisposeStatusAndAlarmType(0, BaseDataConfig.ALARM_FIRE);
		
		return WebResult.OK(alarms);
	}

	// 获取未处理报警
	@RequestMapping(value = "/data/notdispose/welllid")

	public WebResult getNotDisposeBy() {
		List alarms = alarmService.findByDisposeStatusAndAlarmType(0, BaseDataConfig.ALARM_MOVE);
		NotDispose notDispose = new NotDispose();
		
		return WebResult.OK(alarms);
	}

	// 获取未处理的当前用户的烟感火警
	@RequestMapping(value = "/data/notdispose/smoke/{userId}")
	public WebResult getNotDisposeSmokeAlarmByUser(@PathVariable("userId")String userId) {
		System.out.println("userId"+userId);
		List<Alarm> alarms = alarmRepository.getByDisposeStatusAndAlarmTypeAndUser(userId,
				0, BaseDataConfig.ALARM_FIRE);
		System.out.println(alarms.size());
		if(alarms!=null) {
			calculateYOY(userId, 0, BaseDataConfig.ALARM_FIRE);
			calculateYOYByMonth(userId, 0, BaseDataConfig.ALARM_FIRE);
			calculateYOYByQuarter(userId, 0, BaseDataConfig.ALARM_FIRE);
			
		}
		return WebResult.OK(alarms); 
	}

	// 获取未处理的当前用户的阴井盖位移报警
	@RequestMapping(value = "/data/notdispose/humiture/byuser")

	public WebResult getNotDisposeHumitureAlarmByUser() {
		AuthUser user = getLoginUser();
		List<Alarm> alarms = alarmService.getByDisposeStatusAndAlarmTypeAndUser(user.getPeople().getUserId().toString(),
				0, BaseDataConfig.ALARM_Heat);
		return WebResult.OK(alarms);
	}

	// 获取未处理的当前用户的温湿度报警
	@RequestMapping(value = "/data/notdispose/welllid/byuser")

	public WebResult getNotDisposeWelllidAlarmByUser() {
		AuthUser user = getLoginUser();
		List<Alarm> alarms = alarmService.getByDisposeStatusAndAlarmTypeAndUser(user.getPeople().getUserId().toString(),
				0, BaseDataConfig.ALARM_MOVE);
		return WebResult.OK(alarms);
	}

	// 处理报警
	@PostMapping(value = "/data/disposealarm/{devCode}/{alarmId}/{disposeStatus}/{remark}/{alarmReasons}/{name}")

	public WebResult disposeAlarm(HttpServletRequest request, @PathVariable("devCode") String devCode,
			@PathVariable("alarmId") Integer alarmId, @PathVariable("disposeStatus") Integer disposeStatus,
			@PathVariable("remark") String remark, @PathVariable("alarmReasons") String alarmReasons, @PathVariable("name") String name) throws IOException {
		Alarm alarm = alarmService.findOne(alarmId);
		if (alarm != null) {
			SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession()
					.getAttribute("SPRING_SECURITY_CONTEXT");
			
			if (name != null) {
			} else {
				System.out.println("not find user:" + name);
			}

			alarm.setDisposeStatus(disposeStatus);
			if (disposeStatus == 1) {
				alarm.setDisposeContent("处理");
			} else {
				alarm.setDisposeContent("忽略");
			}
			alarm.setDisposeTime(new Date());
			alarm.setDisposePeople(name);
			alarm.setRemark(remark);
			alarm.setAlarmReasons(alarmReasons);
			long begintime = alarm.getBeginTime().getTime();
			long disposeTimetime = alarm.getDisposeTime().getTime();
			double timeDifference = (disposeTimetime - begintime) / 60000.0;
			DecimalFormat df = new DecimalFormat("#.00");
			alarm.setTimeDifference(Double.parseDouble(df.format(timeDifference)));
			alarmService.save(alarm);
		
			return WebResult.OK();
		} else {
			return WebResult.FAIL("not find alarm:" + alarmId.toString());
		}
	}

	// 处理所有报警
	@PostMapping(value = "/data/disposealarmall")

	public WebResult disposeAlarmAll(@PathParam("disposeStatus") Integer disposeStatus) {
		try {
			String name = getLoginUser().getPeople().getName();
			String disposeContent = "";
			if (disposeStatus == 1) {
				disposeContent = "处理";
			} else {
				disposeContent = "忽略";
			}
			alarmService.updateAllDisposeStatus(disposeStatus, name, disposeContent);
			return WebResult.OK();
		} catch (Exception e) {
			// TODO: handle exception
			return WebResult.FAIL(e.getMessage());
		}
	}

	private List<Alarm> getDisposeStatus(Integer disposeStatus) {
		List<Alarm> alarms = alarmService.findByDisposeStatus(disposeStatus);
		return alarms;
	}

	// 按照时间段、组织统计报警原因和数量
	@RequestMapping(value = "/data/org/device/Typecount")

	public WebResult getOrgAlarmCountByType(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmTypeCode") String alarmTypeCode,
			@PathParam("deviceTypeId") String deviceTypeId) {
		String bTime = beginTime;
		String eTime = endTime;

		String userId = this.getUserId();

		List alarms = alarmService.getOrgAlarmCountByAlarmReasons(bTime, eTime, 0, alarmTypeCode, deviceTypeId, userId);
		List result = new ArrayList<>();
		for (Object alarmReasons : alarms) {
			Map value = new HashMap<String, String>();
			Object[] cells = (Object[]) alarmReasons;
			value.put("value", cells[1]);
			value.put("name", cells[0]);
			result.add(value);

		}
		return WebResult.OK(result);

	}

	// 报警原因同比接口
	@RequestMapping(value = "/data/alarmReason/yoy")

	public WebResult getAlarmReason(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode, @PathParam("deviceTypeId") String deviceTypeId,
			@PathParam("alarmReasons") String alarmReasons) throws ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String userId = this.getUserId();
		AlarmReasons result = new AlarmReasons();
		Date bTime = date.parse(beginTime);
		Date eTime = date.parse(endTime);
		long time = (eTime.getTime() - bTime.getTime());
		if (time <= 604800000) {
			result = calculateYOY(alarmTypeCode, deviceTypeId, userId, alarmReasons);
		} else if (time > 604800000 && time < 2592000000l) {
			result = calculateYOYByMonth(alarmTypeCode, deviceTypeId, userId, alarmReasons);
		} else {
			result = calculateYOYByQuarter(alarmTypeCode, deviceTypeId, userId, alarmReasons);
		}

		return WebResult.OK(result);

	}

	// sss
	private AlarmReasons calculateYOYByQuarter(String alarmTypeCode, String deviceTypeId, String userId,
			String alarmReasons) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));
		Date beforeCurrentTime = dataUtil.getBeforeQuarterCurrentTime();// 上季度当前时间
		System.out.println("上季度的当前时间:" + format.format(beforeCurrentTime));
		Date CurrentQuarterTime = dataUtil.getCurrentQuarterStartTime();
		System.out.println("当季度的第一天:" + format.format(CurrentQuarterTime));
		Date beforeCurrentQuarterTime = dataUtil.getBeforeQuarterStartTime();
		System.out.println("上季度的第一天:" + format.format(beforeCurrentQuarterTime));

		DecimalFormat df = new DecimalFormat("#.00");
		AlarmReasons entity = new AlarmReasons();
		List CurrAlarms = alarmService.getOrgAlarmCountByAlarmReasons(format.format(CurrentQuarterTime),
				format.format(currentTime), alarmTypeCode, deviceTypeId, userId, alarmReasons);
		List beforAlarms = alarmService.getOrgAlarmCountByAlarmReasons(format.format(beforeCurrentQuarterTime),
				format.format(beforeCurrentTime), alarmTypeCode, deviceTypeId, userId, alarmReasons);
		for (Object object : beforAlarms) {
			Object[] cells = (Object[]) object;
			entity.setBeforAlarmcount((long) cells[1]);
		}
		for (Object object : CurrAlarms) {
			Object[] cells = (Object[]) object;
			entity.setAlarmReasons((String) cells[0]);
			entity.setCurrAlarmcount((long) cells[1]);
		}
		if (entity.getCurrAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(-entity.getBeforAlarmcount())));
		} else if (entity.getBeforAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(entity.getCurrAlarmcount())));
		} else {

			entity.setValue(Double.parseDouble(df.format((entity.getCurrAlarmcount() - entity.getBeforAlarmcount())
					/ (double) entity.getBeforAlarmcount())));
		}
		entity.setType("一季度" + entity.getAlarmReasons() + "同比");

		alarmReasonsService.deleteByType("一季度" + entity.getAlarmReasons() + "同比");
		alarmReasonsService.save(entity);
		return entity;
	}

	private AlarmReasons calculateYOY(String alarmTypeCode, String deviceTypeId, String userId, String alarmReasons) {
		DecimalFormat df = new DecimalFormat("#.00");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));
		Date beforeCurrentTime = dataUtil.getBeforeWeekCurrentTime();// 上周当前时间
		System.out.println("上周的当前时间:" + format.format(beforeCurrentTime));

		Date CurrentWeekTime = dataUtil.getBeginDayOfWeek();
		Date beforeCurrentWeekTime = dataUtil.getBeforeWeekBeginDayOfWeek();
		System.out.println("上周一时间:" + format.format(beforeCurrentWeekTime));
		AlarmReasons entity = new AlarmReasons();
		List CurrAlarms = alarmService.getOrgAlarmCountByAlarmReasons(format.format(CurrentWeekTime),
				format.format(currentTime), alarmTypeCode, deviceTypeId, userId, alarmReasons);
		List beforAlarms = alarmService.getOrgAlarmCountByAlarmReasons(format.format(beforeCurrentWeekTime),
				format.format(beforeCurrentTime), alarmTypeCode, deviceTypeId, userId, alarmReasons);
		for (Object object : beforAlarms) {
			Object[] cells = (Object[]) object;

			entity.setBeforAlarmcount((long) cells[1]);
		}
		for (Object object : CurrAlarms) {
			Object[] cells = (Object[]) object;
			entity.setAlarmReasons((String) cells[0]);
			entity.setCurrAlarmcount((long) cells[1]);
		}

		if (entity.getCurrAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(-entity.getBeforAlarmcount())));
		} else if (entity.getBeforAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(entity.getCurrAlarmcount())));
		} else {

			entity.setValue(Double.parseDouble(df.format((entity.getCurrAlarmcount() - entity.getBeforAlarmcount())
					/ (double) entity.getBeforAlarmcount())));
		}
		entity.setType("一周" + entity.getAlarmReasons() + "同比");

		alarmReasonsService.deleteByType("一周" + entity.getAlarmReasons() + "同比");
		alarmReasonsService.save(entity);
		return entity;
	}

	private AlarmReasons calculateYOYByMonth(String alarmTypeCode, String deviceTypeId, String userId,
			String alarmReasons) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));

		Date beforeCurrentTime = dataUtil.getBeforeMonthCurrentTime();// 上月当前时间
		System.out.println("上月的当前时间:" + format.format(beforeCurrentTime));

		DecimalFormat df = new DecimalFormat("#.00");
		Date CurrentMonthTime = dataUtil.getTimesMonthmorning();
		System.out.println("本月一号时间:" + format.format(CurrentMonthTime));
		Date beforeCurrentMonthTime = dataUtil.getBeginDayOfLastMonth();
		System.out.println("上月一号时间:" + format.format(beforeCurrentMonthTime));
		AlarmReasons entity = new AlarmReasons();
		List CurrAlarms = alarmService.getOrgAlarmCountByAlarmReasons(format.format(beforeCurrentTime),
				format.format(currentTime), alarmTypeCode, deviceTypeId, userId, alarmReasons);
		List beforAlarms = alarmService.getOrgAlarmCountByAlarmReasons(format.format(beforeCurrentMonthTime),
				format.format(CurrentMonthTime), alarmTypeCode, deviceTypeId, userId, alarmReasons);
		for (Object object : beforAlarms) {
			Object[] cells = (Object[]) object;

			entity.setBeforAlarmcount((long) cells[1]);
		}
		for (Object object : CurrAlarms) {
			Object[] cells = (Object[]) object;
			entity.setAlarmReasons((String) cells[0]);
			entity.setCurrAlarmcount((long) cells[1]);
		}

		if (entity.getCurrAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(-entity.getBeforAlarmcount())));
		} else if (entity.getBeforAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(entity.getCurrAlarmcount())));
		} else {

			entity.setValue(Double.parseDouble(df.format((entity.getCurrAlarmcount() - entity.getBeforAlarmcount())
					/ (double) entity.getBeforAlarmcount())));
		}
		entity.setType("一周" + entity.getAlarmReasons() + "同比");

		alarmReasonsService.deleteByType("一周" + entity.getAlarmReasons() + "同比");
		alarmReasonsService.save(entity);
		return entity;
	}

	private AlarmReasons calculateFixedYOYByQuarter(String alarmTypeCode, String deviceTypeId, String userId,
			String fixedPlace) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));
		Date beforeCurrentTime = dataUtil.getBeforeQuarterCurrentTime();// 上季度当前时间
		System.out.println("上季度的当前时间:" + format.format(beforeCurrentTime));
		DecimalFormat df = new DecimalFormat("#.00");
		Date CurrentQuarterTime = dataUtil.getCurrentQuarterStartTime();
		System.out.println("当季度的第一天:" + format.format(CurrentQuarterTime));
		Date beforeCurrentQuarterTime = dataUtil.getBeforeQuarterStartTime();
		System.out.println("上季度的第一天:" + format.format(beforeCurrentQuarterTime));
		AlarmReasons entity = new AlarmReasons();
		List CurrAlarms = alarmService.getOrgAlarmCountByDevice(format.format(CurrentQuarterTime),
				format.format(currentTime), alarmTypeCode, deviceTypeId, userId, fixedPlace);
		List beforAlarms = alarmService.getOrgAlarmCountByDevice(format.format(beforeCurrentQuarterTime),
				format.format(beforeCurrentTime), alarmTypeCode, deviceTypeId, userId, fixedPlace);

		for (Object object : beforAlarms) {
			Object[] cells = (Object[]) object;
			entity.setBeforAlarmcount((long) cells[1]);
			System.out.println(cells[1]);
		}
		for (Object object : CurrAlarms) {
			Object[] cells = (Object[]) object;
			entity.setAlarmReasons((String) cells[0]);
			entity.setCurrAlarmcount((long) cells[1]);
		}

		if (entity.getCurrAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(-entity.getBeforAlarmcount())));
		} else if (entity.getBeforAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(entity.getCurrAlarmcount())));
		} else {

			entity.setValue(Double.parseDouble(df.format((entity.getCurrAlarmcount() - entity.getBeforAlarmcount())
					/ (double) entity.getBeforAlarmcount())));
		}
		entity.setType("一季度" + entity.getAlarmReasons() + "同比");

		alarmReasonsService.deleteByType("一季度" + entity.getAlarmReasons() + "同比");
		alarmReasonsService.save(entity);
		return entity;
	}

	private AlarmReasons calculateFixedYOYByMonth(String alarmTypeCode, String deviceTypeId, String userId,
			String fixedPlace) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));

		DecimalFormat df = new DecimalFormat("#.00");

		Date beforeCurrentTime = dataUtil.getBeforeMonthCurrentTime();// 上月当前时间
		System.out.println("上月的当前时间:" + format.format(beforeCurrentTime));

		Date CurrentMonthTime = dataUtil.getTimesMonthmorning();
		System.out.println("本月一号时间:" + format.format(CurrentMonthTime));
		Date beforeCurrentMonthTime = dataUtil.getBeginDayOfLastMonth();
		System.out.println("上月一号时间:" + format.format(beforeCurrentMonthTime));
		AlarmReasons entity = new AlarmReasons();
		List CurrAlarms = alarmService.getOrgAlarmCountByDevice(format.format(CurrentMonthTime),
				format.format(currentTime), alarmTypeCode, deviceTypeId, userId, fixedPlace);
		List beforAlarms = alarmService.getOrgAlarmCountByDevice(format.format(beforeCurrentMonthTime),
				format.format(beforeCurrentTime), alarmTypeCode, deviceTypeId, userId, fixedPlace);

		for (Object object : beforAlarms) {
			Object[] cells = (Object[]) object;

			entity.setBeforAlarmcount((long) cells[1]);
		}
		for (Object object : CurrAlarms) {
			Object[] cells = (Object[]) object;
			entity.setAlarmReasons((String) cells[0]);
			entity.setCurrAlarmcount((long) cells[1]);
		}

		if (entity.getCurrAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(-entity.getBeforAlarmcount())));
		} else if (entity.getBeforAlarmcount() == 0) {
			entity.setValue(Double.parseDouble(df.format(entity.getCurrAlarmcount())));
		} else {

			entity.setValue(Double.parseDouble(df.format((entity.getCurrAlarmcount() - entity.getBeforAlarmcount())
					/ (double) entity.getBeforAlarmcount())));
		}
		entity.setType("一月" + entity.getAlarmReasons() + "同比");

		alarmReasonsService.deleteByType("一月" + entity.getAlarmReasons() + "同比");
		alarmReasonsService.save(entity);
		return entity;
	}

	private AlarmReasons calculateFixedYOY(String alarmTypeCode, String deviceTypeId, String userId,
			String fixedPlace) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));
		Date beforeCurrentTime = dataUtil.getBeforeWeekCurrentTime();// 上周当前时间
		System.out.println("上周的当前时间:" + format.format(beforeCurrentTime));

		Date CurrentWeekTime = dataUtil.getBeginDayOfWeek();
		Date beforeCurrentWeekTime = dataUtil.getBeforeWeekBeginDayOfWeek();
		System.out.println("上周一时间:" + format.format(beforeCurrentWeekTime));
		AlarmReasons entity = new AlarmReasons();

		List CurrAlarms = alarmService.getOrgAlarmCountByDevice(format.format(CurrentWeekTime),
				format.format(currentTime), alarmTypeCode, deviceTypeId, userId, fixedPlace);
		List beforAlarms = alarmService.getOrgAlarmCountByDevice(format.format(beforeCurrentWeekTime),
				format.format(beforeCurrentTime), alarmTypeCode, deviceTypeId, userId, fixedPlace);
		DecimalFormat df = new DecimalFormat("#.00");

		for (Object object : beforAlarms) {
			Object[] cells = (Object[]) object;

			entity.setBeforAlarmcount((long) cells[1]);
		}
		for (Object object : CurrAlarms) {
			Object[] cells = (Object[]) object;
			entity.setAlarmReasons((String) cells[0]);
			entity.setCurrAlarmcount((long) cells[1]);
		}

		if (entity.getCurrAlarmcount() == 0) {
			entity.setValue(-entity.getBeforAlarmcount());
		} else if (entity.getBeforAlarmcount() == 0) {
			entity.setValue(entity.getCurrAlarmcount());
		} else {

			entity.setValue(Double.parseDouble(df.format((entity.getCurrAlarmcount() - entity.getBeforAlarmcount())
					/ (double) entity.getBeforAlarmcount())));
		}
		entity.setType("一周" + entity.getAlarmReasons() + "同比");

		alarmReasonsService.deleteByType("一周" + entity.getAlarmReasons() + "同比");
		alarmReasonsService.save(entity);
		return entity;
	}

	// 按照时间段、组织统计报警来源和数量
	@RequestMapping(value = "/data/org/device/fixcount")

	public WebResult getDeviceCountByFixedPlace(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmTypeCode") String alarmTypeCode,
			@PathParam("deviceTypeId") String deviceTypeId) {
		String bTime = beginTime;
		String eTime = endTime;

		String userId = this.getUserId();

		List alarms = alarmService.getOrgAlarmCountByDevice(bTime, eTime, 0, alarmTypeCode, deviceTypeId, userId);
		List result = new ArrayList<>();
		for (Object fixedPlace : alarms) {
			Map value = new HashMap<String, String>();
			Object[] cells = (Object[]) fixedPlace;
			value.put("value", cells[1]);
			value.put("name", cells[0]);
			result.add(value);

		}
		return WebResult.OK(result);

	}

	// 报警场所同比接口
	@RequestMapping(value = "/data/fixedPlace/yoy")

	// bb
	public WebResult getFixedPlaceYoy(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode, @PathParam("deviceTypeId") String deviceTypeId,
			@PathParam("fixedPlace") String fixedPlace) throws ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String userId = this.getUserId();
		AlarmReasons result = new AlarmReasons();
		Date bTime = date.parse(beginTime);
		Date eTime = date.parse(endTime);
		long time = (eTime.getTime() - bTime.getTime());
		List alarms = alarmService.getOrgAlarmCountByDevice(date.format(bTime), date.format(eTime), alarmTypeCode,
				deviceTypeId, userId, fixedPlace);
		for (Object object : alarms) {
			Object[] cells = (Object[]) object;
		}
		if (time <= 604800000) {
			result = calculateFixedYOY(alarmTypeCode, deviceTypeId, userId, fixedPlace);
		} else if (time > 604800000 && time < 2592000000l) {
			result = calculateFixedYOYByMonth(alarmTypeCode, deviceTypeId, userId, fixedPlace);
		} else {
			result = calculateFixedYOYByQuarter(alarmTypeCode, deviceTypeId, userId, fixedPlace);
		}
		return WebResult.OK(result);

	}

	private void calculateYOY(String userId, Integer status, String alarmCode) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));
		Date beforeCurrentTime = dataUtil.getBeforeWeekCurrentTime();// 上周当前时间
		System.out.println("上周的当前时间:" + format.format(beforeCurrentTime));

		Date CurrentWeekTime = dataUtil.getBeginDayOfWeek();
		Date beforeCurrentWeekTime = dataUtil.getBeforeWeekBeginDayOfWeek();
		System.out.println("上周一时间:" + format.format(beforeCurrentWeekTime));
		List<Alarm> secondCount = alarmService.getByTimeAndDisposeStatusAndAlarmTypeAndUser(
				format.format(CurrentWeekTime), format.format(currentTime), userId, status, alarmCode);
		List<Alarm> firstCount = alarmService.getByTimeAndDisposeStatusAndAlarmTypeAndUser(
				format.format(beforeCurrentWeekTime), format.format(beforeCurrentTime), userId, status, alarmCode);
		Yoy yoy = new Yoy();
		yoy.setSecondCount(secondCount.size());
		yoy.setFirstCount(firstCount.size());
		if (secondCount.size() == 0) {
			yoy.setValue(-firstCount.size());
		} else if (firstCount.size() == 0) {
			yoy.setValue(secondCount.size());
		} else {

			yoy.setValue((secondCount.size() - firstCount.size()) / (double) firstCount.size());
		}
		yoy.setType("一周未处理数同比");

		yoyService.deleteByType("一周未处理数同比");
		yoyService.save(yoy);
	}

	// 存入一月未处理同比
	private void calculateYOYByMonth(String userId, Integer status, String alarmCode) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));

		Date beforeCurrentTime = dataUtil.getBeforeMonthCurrentTime();// 上月当前时间
		System.out.println("上月的当前时间:" + format.format(beforeCurrentTime));

		Date CurrentMonthTime = dataUtil.getTimesMonthmorning();
		System.out.println("本月一号时间:" + format.format(CurrentMonthTime));
		Date beforeCurrentMonthTime = dataUtil.getBeginDayOfLastMonth();
		System.out.println("上月一号时间:" + format.format(beforeCurrentMonthTime));
		List<Alarm> secondCount = alarmService.getByTimeAndDisposeStatusAndAlarmTypeAndUser(
				format.format(CurrentMonthTime), format.format(currentTime), userId, status, alarmCode);
		List<Alarm> firstCount = alarmService.getByTimeAndDisposeStatusAndAlarmTypeAndUser(
				format.format(beforeCurrentMonthTime), format.format(beforeCurrentTime), userId, status, alarmCode);
		Yoy yoy = new Yoy();
		yoy.setSecondCount(secondCount.size());
		yoy.setFirstCount(firstCount.size());
		if (secondCount.size() == 0) {
			yoy.setValue(-firstCount.size());
		} else if (firstCount.size() == 0) {
			yoy.setValue(secondCount.size());
		} else {

			yoy.setValue((secondCount.size() - firstCount.size()) / (double) firstCount.size());
		}
		yoy.setType("一月未处理数同比");

		yoyService.deleteByType("一月未处理数同比");
		yoyService.save(yoy);
	}

	// 存入一季度报警同比时间
	private void calculateYOYByQuarter(String userId, Integer status, String alarmCode) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		Date currentTime = dataUtil.getCurrentTime();// 当前时间
		System.out.println("当前时间:" + format.format(currentTime));
		Date beforeCurrentTime = dataUtil.getBeforeQuarterCurrentTime();// 上季度当前时间
		System.out.println("上季度的当前时间:" + format.format(beforeCurrentTime));
		Date CurrentQuarterTime = dataUtil.getCurrentQuarterStartTime();
		System.out.println("当季度的第一天:" + format.format(CurrentQuarterTime));
		Date beforeCurrentQuarterTime = dataUtil.getBeforeQuarterStartTime();
		System.out.println("上季度的第一天:" + format.format(beforeCurrentQuarterTime));
		List<Alarm> secondCount = alarmService.getByTimeAndDisposeStatusAndAlarmTypeAndUser(
				format.format(CurrentQuarterTime), format.format(currentTime), userId, status, alarmCode);
		List<Alarm> firstCount = alarmService.getByTimeAndDisposeStatusAndAlarmTypeAndUser(
				format.format(beforeCurrentQuarterTime), format.format(beforeCurrentTime), userId, status, alarmCode);
		Yoy yoy = new Yoy();
		yoy.setSecondCount(secondCount.size());
		yoy.setFirstCount(firstCount.size());
		DecimalFormat df = new DecimalFormat("#.00");
		if (secondCount.size() == 0) {
			yoy.setValue(Double.parseDouble(df.format(-firstCount.size())));
		} else if (firstCount.size() == 0) {
			yoy.setValue(Double.parseDouble(df.format(secondCount.size())));
		} else {

			yoy.setValue(Double
					.parseDouble(df.format((secondCount.size() - firstCount.size()) / (double) firstCount.size())));
		}
		yoy.setType("一季度未处理数同比");

		yoyService.deleteByType("一季度未处理数同比");
		yoyService.save(yoy);
	}

}
